﻿Imports Microsoft.SharePoint.Administration
Imports Microsoft.SharePoint
Imports System.IO
Imports Microsoft.SharePoint.Utilities
Imports System.Runtime.CompilerServices
Imports System.Security.Principal
Imports Bengen.SP.ImportDataTimer.Extensions.SPListItemExensions

''' <summary>
''' 
''' </summary>
''' <remarks>
''' For permission issues that occur while trying to open connections see this post:
''' http://social.msdn.microsoft.com/forums/en-US/sqldatabaseengine/thread/b9ad4df2-b256-4a33-911b-a06001250f9e/
''' 
''' Another project which helped me get started as well as installing a custom timer job:
''' http://efworkflowtimer.codeplex.com/
''' Theres probably some remnants of fangdahai's code here.
''' 
'''</remarks>

Public Class ImportDataTimerJob
    Inherits SPJobDefinition

#Region "Declarations"

    Public Const JOB_NAME As String = "ImportDataTimerJob"
    Public Const JOB_DESCRIPTION As String = "Import data timer job."
    Public Const HISTORY_LIST_TITLE As String = "ImportDataTimerHistory"
    Public Const SETTINGS_LIST_TITLE As String = "ImportDataTimerSettings"
    'Public Const RESULTS_LIST_TITLE As String = "ImportDataTimerResults"

#End Region

#Region "Construction"

    Public Sub New(ByVal jobName As String, ByVal service As SPService, ByVal server As SPServer, ByVal targetType As SPJobLockType)
        MyBase.New(jobName, service, server, targetType)
    End Sub

    Public Sub New(ByVal jobName As String, ByVal webApplication As SPWebApplication)
        MyBase.New(jobName, webApplication, Nothing, SPJobLockType.ContentDatabase)
        Me.Title = jobName
    End Sub

    Public Sub New()
        MyBase.New(JOB_NAME, SPFarm.Local.TimerService, Nothing, SPJobLockType.None)
    End Sub

#End Region

#Region "Methods"

    Public Overrides ReadOnly Property Description As String
        Get
            Return "Imports the results from SQL statements on recurring schedules."
        End Get
    End Property

    Public Overrides ReadOnly Property DisplayName As String
        Get
            Return "Import data timer job"
        End Get
    End Property

#End Region

#Region "Timer Execution"

    Public Overrides Sub Execute(ByVal targetInstanceId As System.Guid)
        Dim webApplication As SPWebApplication = TryCast(Me.Parent, SPWebApplication)
        Dim contentDb As SPContentDatabase = webApplication.ContentDatabases(targetInstanceId)

        Using s As SPSite = New SPSite(contentDb.Sites(0).Url)
            'Open the root web of the site collection
            '  This is the web that should contain the configuration lists
            Using w As SPWeb = s.OpenWeb()
                'Retrieve and iterate items
                For Each item As SPListItem In GetItemsToExecute(w, w.Lists.TryGetList(SETTINGS_LIST_TITLE))
                    Try
                        Dim job As New Job(item)
                        job.DoJob()
                    Catch ex As Exception
                    End Try
                Next
            End Using
        End Using
    End Sub

    Private Function GetItemsToExecute(ByVal web As SPWeb, ByVal list As SPList) As SPListItemCollection
        'DateFilter is a calculated field on the 'Recurrence' field.
        Dim query As New SPQuery
        query.Query = String.Format("<Where><Or><And><Leq><FieldRef Name='DateFilter' /><Value Type='Calculated'>{0}</Value></Leq><Eq><FieldRef Name='Status' /><Value Type='Choice'>Active</Value></Eq></And><Eq><FieldRef Name='Status' /><Value Type='Choice'>Test</Value></Eq></Or></Where>", DateTime.Now.ToString("yyyyMMddHHmmss"))
        Return list.GetItems(query)
    End Function

#End Region

End Class
